package com.liam.rabbitmqdemo.rabbitmq.topic;

import com.liam.rabbitmqdemo.rabbitmq.constant.Constants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: LiamLMK
 * @CreateTime: 2025-03-03
 * @Description:
 * @Version: 1.0
 */

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT); // 需要提前开放端口号
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); // 虚拟主机
        Connection connection = connectionFactory.newConnection();
        // 2. 开启信道
        Channel channel = connection.createChannel();
        // 3. 声明交换机Exchange（使用内置的交换机）
        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC, true);
        // 4. 声明队列Queue
        channel.queueDeclare(Constants.TOPIC_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPIC_QUEUE2, true, false, false, null);
        // 5. 交换机和队列绑定
        channel.queueBind(Constants.TOPIC_QUEUE1, Constants.TOPIC_EXCHANGE, "*.a.*");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "*.*.b");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "c.#");
        // 发布消息
//        for (int i = 0; i < 10; i++) {
        String msgA = "hello topic, routing key is ae.a.f...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "ae.a.f", null, msgA.getBytes());
        String msgB = "hello topic, routing key is cw.a.b...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "cw.a.b", null, msgB.getBytes());
        String msgC = "hello topic, routing key is c.ef.d...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "c.ef.d", null, msgC.getBytes());
            System.out.println("消息发送成功");
//        }
        // 7. 资源释放
        channel.close();
        connection.close();
    }
}
